import React, {Component} from 'react';
import './index.less';
import {
    base,
    toast,
    high,
    promptBox,
    output,
    print,
    cacheTools
} from 'nc-lightapp-front';

import CenterTree from "./functions/CenterTree";
import CenterTreeFirstChildAction from "./functions/CenterTreeFirstChildAction";
import {getAllTreeRefpk} from "../../main/common";

const treeId = 'treeid';

class LeftTree extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json: props.json,
            treeData: [], // 左树数据

            checkedKeys: [], // 左树选中的分支
        };
    }

    componentWillReceiveProps(nextprops) {
        let nextjson = JSON.stringify(nextprops.json);
        let thisjson = JSON.stringify(this.props.json);
        if (nextjson !== thisjson) {
            this.setState({
                json: nextprops.json
            })
        }
        // 人力资源组织 发生变化 左树重新请求
        if (nextprops.hrorgval !== this.props.hrorgval) {
            this.getTreeData(nextprops.hrorgval);
        }
    }

    /**
     * 左树获取数据
     */
    getTreeData = (hrorgval) => {
        this.props.emptyRightTable();
        // 请求左树数据
        CenterTree(hrorgval || this.props.hrorgval).then(res => {
            if (res['data'] && Array.isArray(res['data'])) {
                // this.setState({
                //     treeData: res['data']
                // })
                this.creatTree(res['data'])
            }
        })
    };

    /**
     * 创建左边导航栏
     */
    creatTree(navData) {
        let root = {//树根节点
            "isleaf": false,
            "select": true,
            "key": "ROOT",
            "title": this.state.json['cm6011-000002'],
            "id": "ROOT",
            "innercode": "ROOT",
            "pid": "",
            "refname": this.state.json['cm6011-000002'],
            "refpk": "ROOT",
            "iconBox": {addIcon: false, delIcon: false, editIcon: false}
        };
        if (navData) {
            root.children = navData;
        }
        let treeData = [root];
        this.props.asyncTree.setTreeData(treeId, treeData);
        this.props.asyncTree.setNodeSelectedAsync(treeId,root.refpk);
        this.props.refresh();
    }

    /**
     * 选择树节点
     */
    selectTree = (refpk, item) => {
        let deptPk = null, orgPk = null, isOtherNode = false;
        // 清空表单
        if (refpk[0] !== 'ROOT') {
            // 如果没有改变则返回
            isOtherNode = refpk[0] === 'other_node_msaos';
            let nodeVal = item.nodeData.nodeValue;
            deptPk = nodeVal.hasOwnProperty('pk_dept') ? nodeVal.pk_dept : null;
            orgPk = isOtherNode ? null : (nodeVal.hasOwnProperty('pk_org') ? nodeVal.pk_org : null);
        }
        if (deptPk) {
            orgPk = null;
        }
        this.props.updateState({
            orgPk,
            deptPk,
            isOtherNode
        })
    };

    loadTreeData = (refpk) => {
        if (refpk === 'ROOT') {
            return;
        }
        CenterTreeFirstChildAction(refpk, this.props.hrorgval).then(res => {
            if (!res.data) return;
            let allRefpk = getAllTreeRefpk(this.props, treeId);
            let addTreeData = [];
            res.data.map(item=>{
                if(!allRefpk.includes(item.refpk)){
                    addTreeData.push(item)
                }
                if(!allRefpk.includes(item.pid)){
                    item.pid='ROOT'
                }
            });
            this.props.asyncTree.addTreeData(treeId, addTreeData);
        })
    };

    render() {
        let {asyncTree} = this.props;
        const {createAsyncTree} = asyncTree;
        return (
            <div className="left-tree">
                <div className="tree-area">
                    {JSON.stringify(this.state.json) !== '{}' ? < div className={'tree-warp'}>
                        {createAsyncTree({
                            treeId: treeId,
                            needSearch: false, //是否需要搜索框
                            needEdit: false, //不启用编辑
                            showLine: false, //显示连线
                            defaultSelectedKeys: ["ROOT"],
                            onSelectedChange: (node) => {
                                if (!node) {
                                    this.props.asyncTree.openNodeByPkAsync(treeId, "ROOT")
                                }
                            },
                            onSelectEve: this.selectTree.bind(this), //节点选中事件
                            loadTreeData: this.loadTreeData.bind(this), //加载子节点数据
                            showModal: false //是否使用弹出式编辑
                        })}
                    </div> : null}
                </div>
            </div>
        );
    }
}

export default LeftTree;
